// 模拟延迟
const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))

// 数据类型定义
interface QuestionBank {
  id: number
  name: string
  createdAt: string
}

interface Question {
  id: number
  title: string
  type: string
  difficulty: string
  bankId: number
  answer: string
}

interface Exam {
  id: number
  name: string
  startTime: string
  endTime: string
  status: string
}

interface User {
  id: number
  username: string
  email: string
  role: string
}

interface Result {
  id: number
  studentName: string
  examName: string
  score: number
  totalScore: number
  rank: number
}

// 模拟数据
let questionBanks: QuestionBank[] = [
  { id: 1, name: "JavaScript基础", createdAt: "2023-01-01T00:00:00Z" },
  { id: 2, name: "Vue.js进阶", createdAt: "2023-02-01T00:00:00Z" },
]

let questions: Question[] = [
  {
    id: 1,
    title: "什么是Vue.js?",
    type: "单选题",
    difficulty: "简单",
    bankId: 2,
    answer: "Vue.js是一个用于构建用户界面的渐进式框架",
  },
  { id: 2, title: "Vue.js的核心库只关注哪一层?", type: "单选题", difficulty: "中等", bankId: 2, answer: "视图层" },
  {
    id: 3,
    title: "Vue.js支持哪些指令?",
    type: "多选题",
    difficulty: "中等",
    bankId: 2,
    answer: "v-if, v-for, v-model, v-on, v-bind",
  },
  {
    id: 4,
    title: "JavaScript中的数据类型有哪些?",
    type: "多选题",
    difficulty: "简单",
    bankId: 1,
    answer: "Number, String, Boolean, Object, Array, Null, Undefined",
  },
]

let exams: Exam[] = [
  { id: 1, name: "Vue.js基础考试", startTime: "2023-06-01T09:00", endTime: "2023-06-01T11:00", status: "已结束" },
  { id: 2, name: "JavaScript进阶考试", startTime: "2023-12-15T14:00", endTime: "2023-12-15T16:00", status: "未开始" },
]

let users: User[] = [
  { id: 1, username: "student1", email: "student1@example.com", role: "学生" },
  { id: 2, username: "teacher1", email: "teacher1@example.com", role: "教师" },
]

let results: Result[] = [
  { id: 1, studentName: "张三", examName: "Vue.js基础考试", score: 85, totalScore: 100, rank: 1 },
  { id: 2, studentName: "李四", examName: "Vue.js基础考试", score: 78, totalScore: 100, rank: 2 },
]

// API 函数
export const api = {
  async getQuestionBanks(): Promise<QuestionBank[]> {
    await delay(300)
    return [...questionBanks]
  },

  async addQuestionBank(bank: Omit<QuestionBank, 'id' | 'createdAt'>): Promise<QuestionBank> {
    await delay(300)
    const newBank: QuestionBank = { ...bank, id: questionBanks.length + 1, createdAt: new Date().toISOString() }
    questionBanks.push(newBank)
    return newBank
  },

  async updateQuestionBank(id: number, bank: Partial<QuestionBank>): Promise<QuestionBank> {
    await delay(300)
    const index = questionBanks.findIndex((b) => b.id === id)
    if (index !== -1) {
      questionBanks[index] = { ...questionBanks[index], ...bank }
      return questionBanks[index]
    }
    throw new Error("Question bank not found")
  },

  async deleteQuestionBank(id: number): Promise<{ success: boolean }> {
    await delay(300)
    questionBanks = questionBanks.filter((b) => b.id !== id)
    questions = questions.filter((q) => q.bankId !== id)
    return { success: true }
  },

  async getQuestions(bankId: number | null = null): Promise<Question[]> {
    await delay(300)
    return bankId ? questions.filter((q) => q.bankId === bankId) : [...questions]
  },

  async addQuestion(question: Omit<Question, 'id'>): Promise<Question> {
    await delay(300)
    const newQuestion: Question = { ...question, id: questions.length + 1 }
    questions.push(newQuestion)
    return newQuestion
  },

  async updateQuestion(id: number, question: Partial<Question>): Promise<Question> {
    await delay(300)
    const index = questions.findIndex((q) => q.id === id)
    if (index !== -1) {
      questions[index] = { ...questions[index], ...question }
      return questions[index]
    }
    throw new Error("Question not found")
  },

  async deleteQuestion(id: number): Promise<{ success: boolean }> {
    await delay(300)
    questions = questions.filter((q) => q.id !== id)
    return { success: true }
  },

  async getExams(): Promise<Exam[]> {
    await delay(300)
    return [...exams]
  },

  async addExam(exam: Omit<Exam, 'id'>): Promise<Exam> {
    await delay(300)
    const newExam: Exam = { ...exam, id: exams.length + 1 }
    exams.push(newExam)
    return newExam
  },

  async updateExam(id: number, exam: Partial<Exam>): Promise<Exam> {
    await delay(300)
    const index = exams.findIndex((e) => e.id === id)
    if (index !== -1) {
      exams[index] = { ...exams[index], ...exam }
      return exams[index]
    }
    throw new Error("Exam not found")
  },

  async deleteExam(id: number): Promise<{ success: boolean }> {
    await delay(300)
    exams = exams.filter((e) => e.id !== id)
    return { success: true }
  },

  async getUsers(): Promise<User[]> {
    await delay(300)
    return [...users]
  },

  async getResults(): Promise<Result[]> {
    await delay(300)
    return [...results]
  },

  async generateExamPaper(examId: number, bankId: number, questionCount: number): Promise<{ examId: number, questions: Question[] }> {
    await delay(500)
    const bankQuestions = questions.filter((q) => q.bankId === bankId)
    const selectedQuestions = bankQuestions.sort(() => 0.5 - Math.random()).slice(0, questionCount)
    return {
      examId,
      questions: selectedQuestions,
    }
  },

  async submitExamResult(result: Omit<Result, 'id'>): Promise<Result> {
    await delay(300)
    const newResult: Result = { ...result, id: results.length + 1 }
    results.push(newResult)
    return newResult
  },
}
